package com.kexio.user.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kexio.auth.annotation.RequiresPermission;
import com.kexio.common.dto.PageResponse;
import com.kexio.common.dto.Result;
import com.kexio.user.dto.TenantDTO;
import com.kexio.user.entity.Tenant;
import com.kexio.user.service.TenantService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;

/**
 * 租户管理控制器
 * 
 * 提供多租户系统的租户管理功能，包括：
 * - 租户的创建、查询、更新、删除
 * - 租户状态管理
 * - 租户用户统计
 * - 租户配置管理
 * 
 * @author Kexio Team
 * @since 1.0.0
 */
@RestController
@RequestMapping("/tenants")
@Tag(name = "租户管理", description = "多租户系统的租户管理API")
public class TenantController {
    
    private static final Logger logger = LoggerFactory.getLogger(TenantController.class);
    
    @Autowired
    private TenantService tenantService;
    
    /**
     * 创建新租户
     */
    @PostMapping
    @RequiresPermission("system:tenant:create")
    @Operation(summary = "创建租户", description = "创建新的租户实例")
    public Result<TenantDTO> createTenant(
            @Valid @RequestBody TenantDTO request) {
        
        logger.info("创建租户请求: tenantId={}, tenantName={}", 
            request.getTenantId(), request.getTenantName());
        
        // 验证请求参数
        request.validate();
        
        // 创建租户
        Tenant tenant = tenantService.createTenant(request);
        
        // 转换为响应DTO
        TenantDTO response = TenantDTO.fromEntity(tenant);
        
        logger.info("创建租户成功: tenantId={}", tenant.getTenantId());
        return Result.success("租户创建成功", response);
    }
    
    /**
     * 获取租户列表（分页）
     */
    @GetMapping
    @RequiresPermission("system:tenant:list")
    @Operation(summary = "获取租户列表", description = "分页查询租户列表")
    public Result<PageResponse<TenantDTO>> getTenantList(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Long current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Long size,
            @Parameter(description = "租户名称（模糊搜索）") @RequestParam(required = false) String tenantName,
            @Parameter(description = "租户状态") @RequestParam(required = false) Integer status) {
        
        logger.debug("获取租户列表请求: current={}, size={}, tenantName={}, status={}", 
            current, size, tenantName, status);
        
        // 分页查询租户
        Page<Tenant> page = tenantService.getTenantPage(current, size, tenantName, status, null);
        
        // 转换为DTO分页响应
        PageResponse<TenantDTO> response = PageResponse.of(
            page.getRecords().stream()
                .map(TenantDTO::fromEntity)
                .toList(),
            page.getCurrent(),
            page.getSize(), 
            page.getTotal()
        );
        
        // 填充用户数量统计
        response.getRecords().forEach(dto -> {
            int userCount = tenantService.getUserCountByTenantId(dto.getTenantId());
            dto.setUserCount(userCount);
        });
        
        logger.debug("获取租户列表成功: total={}", response.getTotal());
        return Result.success("获取租户列表成功", response);
    }
    
    /**
     * 获取租户详情
     */
    @GetMapping("/{tenantId}")
    @RequiresPermission("system:tenant:read")
    @Operation(summary = "获取租户详情", description = "根据租户ID获取租户详细信息")
    public Result<TenantDTO> getTenantDetails(
            @Parameter(description = "租户ID") @PathVariable String tenantId) {
        
        logger.debug("获取租户详情请求: tenantId={}", tenantId);
        
        Tenant tenant = tenantService.getTenantByTenantId(tenantId);
        
        if (tenant == null) {
            logger.warn("租户不存在: tenantId={}", tenantId);
            return Result.error("租户不存在");
        }
        
        TenantDTO response = TenantDTO.fromEntity(tenant);
        
        logger.debug("获取租户详情成功: tenantId={}", tenantId);
        return Result.success("获取租户详情成功", response);
    }
    
    /**
     * 更新租户信息
     */
    @PutMapping("/{tenantId}")
    @RequiresPermission("system:tenant:update")
    @Operation(summary = "更新租户", description = "更新租户基本信息")
    public Result<TenantDTO> updateTenant(
            @Parameter(description = "租户ID") @PathVariable String tenantId,
            @Valid @RequestBody TenantDTO request) {
        
        logger.info("更新租户请求: tenantId={}, tenantName={}", 
            tenantId, request.getTenantName());
        
        // 验证请求参数
        request.validate();
        
        // 更新租户
        Tenant tenant = tenantService.updateTenant(tenantId, request);
        
        // 转换为响应DTO
        TenantDTO response = TenantDTO.fromEntity(tenant);
        
        logger.info("更新租户成功: tenantId={}", tenantId);
        return Result.success("租户更新成功", response);
    }
    
    /**
     * 删除租户
     */
    @DeleteMapping("/{tenantId}")
    @RequiresPermission("system:tenant:delete")
    @Operation(summary = "删除租户", description = "删除指定租户（软删除）")
    public Result<Void> deleteTenant(
            @Parameter(description = "租户ID") @PathVariable String tenantId) {
        
        logger.info("删除租户请求: tenantId={}", tenantId);
        
        // 删除租户（软删除）
        boolean deleted = tenantService.deleteTenant(tenantId);
        
        if (deleted) {
            logger.info("删除租户成功: tenantId={}", tenantId);
            return Result.success("租户删除成功");
        } else {
            logger.warn("删除租户失败: tenantId={}", tenantId);
            return Result.error("删除租户失败");
        }
    }
    
    /**
     * 更新租户状态
     */
    @PutMapping("/{tenantId}/status")
    @RequiresPermission("system:tenant:update-status")
    @Operation(summary = "更新租户状态", description = "启用/禁用租户")
    public Result<Void> updateTenantStatus(
            @Parameter(description = "租户ID") @PathVariable String tenantId,
            @Parameter(description = "租户状态") @RequestParam Integer status) {
        
        logger.info("更新租户状态请求: tenantId={}, status={}", tenantId, status);
        
        // 更新租户状态
        boolean updated = tenantService.updateTenantStatus(tenantId, status);
        
        if (updated) {
            logger.info("更新租户状态成功: tenantId={}, status={}", tenantId, status);
            return Result.success("租户状态更新成功");
        } else {
            logger.warn("更新租户状态失败: tenantId={}, status={}", tenantId, status);
            return Result.error("更新租户状态失败");
        }
    }
    
    /**
     * 获取租户用户统计
     */
    @GetMapping("/{tenantId}/stats")
    @RequiresPermission("system:tenant:stats")
    @Operation(summary = "获取租户统计", description = "获取租户下的用户统计信息")
    public Result<TenantStatsDTO> getTenantStats(
            @Parameter(description = "租户ID") @PathVariable String tenantId) {
        
        logger.debug("获取租户统计请求: tenantId={}", tenantId);
        
        // 检查租户是否存在
        if (!tenantService.existsByTenantId(tenantId)) {
            return Result.error("租户不存在");
        }
        
        // 获取统计信息
        int userCount = tenantService.getUserCountByTenantId(tenantId);
        boolean canAddUsers = tenantService.canAddMoreUsers(tenantId);
        int remainingQuota = tenantService.getRemainingUserQuota(tenantId);
        
        TenantStatsDTO stats = new TenantStatsDTO();
        stats.setTenantId(tenantId);
        stats.setUserCount(userCount);
        stats.setActiveUserCount(userCount); // 简化处理，实际应查询活跃用户数
        
        // 查询角色统计（简化版，返回启用的角色数量）
        stats.setRoleCount(0); // 暂时返回0，后续可通过RoleService统计
        
        // 最后活跃时间（暂时返回当前时间，后续可通过用户最后登录时间统计）
        stats.setLastActiveTime(java.time.LocalDateTime.now().toString());
        
        // 添加扩展信息（非标准字段）
        stats.setCanAddUsers(canAddUsers);
        stats.setRemainingQuota(remainingQuota);
        
        logger.debug("获取租户统计成功: tenantId={}, userCount={}", tenantId, userCount);
        return Result.success("获取租户统计成功", stats);
    }
    
    /**
     * 获取可用租户列表（用于下拉选择）
     */
    @GetMapping("/options")
    @RequiresPermission("system:tenant:list")
    @Operation(summary = "获取租户选项", description = "获取可用的租户列表，用于下拉选择")
    public Result<List<TenantOptionDTO>> getTenantOptions() {
        
        logger.debug("获取租户选项请求");
        
        // 获取所有活跃租户
        List<Tenant> activeTenants = tenantService.getActiveTenants();
        
        // 转换为选项DTO
        List<TenantOptionDTO> options = activeTenants.stream()
            .map(tenant -> {
                TenantOptionDTO option = new TenantOptionDTO();
                option.setTenantId(tenant.getTenantId());
                option.setTenantName(tenant.getTenantName());
                option.setStatus(tenant.getStatus());
                return option;
            })
            .toList();
        
        logger.debug("获取租户选项成功: count={}", options.size());
        return Result.success("获取租户选项成功", options);
    }
    
    // ==================== 内部DTO类 ====================
    
    /**
     * 租户统计DTO
     */
    public static class TenantStatsDTO {
        private String tenantId;
        private Integer userCount;
        private Integer roleCount;
        private Integer activeUserCount;
        private String lastActiveTime;
        
        // 扩展字段
        private Boolean canAddUsers;
        private Integer remainingQuota;
        
        // Getters and Setters
        public String getTenantId() { return tenantId; }
        public void setTenantId(String tenantId) { this.tenantId = tenantId; }
        
        public Integer getUserCount() { return userCount; }
        public void setUserCount(Integer userCount) { this.userCount = userCount; }
        
        public Integer getRoleCount() { return roleCount; }
        public void setRoleCount(Integer roleCount) { this.roleCount = roleCount; }
        
        public Integer getActiveUserCount() { return activeUserCount; }
        public void setActiveUserCount(Integer activeUserCount) { this.activeUserCount = activeUserCount; }
        
        public String getLastActiveTime() { return lastActiveTime; }
        public void setLastActiveTime(String lastActiveTime) { this.lastActiveTime = lastActiveTime; }
        
        public Boolean getCanAddUsers() { return canAddUsers; }
        public void setCanAddUsers(Boolean canAddUsers) { this.canAddUsers = canAddUsers; }
        
        public Integer getRemainingQuota() { return remainingQuota; }
        public void setRemainingQuota(Integer remainingQuota) { this.remainingQuota = remainingQuota; }
    }
    
    /**
     * 租户选项DTO
     */
    public static class TenantOptionDTO {
        private String tenantId;
        private String tenantName;
        private Integer status;
        
        // Getters and Setters
        public String getTenantId() { return tenantId; }
        public void setTenantId(String tenantId) { this.tenantId = tenantId; }
        
        public String getTenantName() { return tenantName; }
        public void setTenantName(String tenantName) { this.tenantName = tenantName; }
        
        public Integer getStatus() { return status; }
        public void setStatus(Integer status) { this.status = status; }
    }
}
